<?php

namespace App\Http\Controllers\Admin\System {


use App\Http\Controllers\Controller;
use App\Http\Resources\System\SysUserResources;
use App\Services\System\SysUserService;
use App\Models\System\SysUserModel;
use App\Validate\System\SysUserValidate;
use Exception;
use OpenApi\Attributes as OA;

/**
* 用户信息表 控制器
* @create 2023-07-24 10:47:15
*/
class SysUserController extends Controller {
    

    public function index() {
        return new SysUserResources(SysUserModel::paginate());
        $rows = SysUserModel::selectList($this->pag(), request()->all());
        return self::bean($rows);
    }
            
    /** 新增 */
    public function store() {
        SysUserValidate::scene('store');
        
        $row = SysUserModel::insertData(request()->all());
        return self::bean($row);
    }

    /** 更新 */
    public function update() {
        SysUserValidate::scene('update');
        
        $row = SysUserModel::updateData(request('id'), request()->all());
        return self::bean($row);
    }
            
    /** 详情 */
    public function show($user_id) {
        $row = SysUserModel::selectByUserId($user_id);
        return self::bean($row);
    }
            
    /** 删除 */
    public function destroy($user_ids) {
        $user_ids = explode(',', $user_ids);
        $suc = []; $err = [];
        foreach($user_ids as $id) {
            try {
                $suc[] = SysUserModel::deleteData($id);
            } catch(Exception $e) {
                $err[] = ['user_id'=>$id, 'msg'=>$e->getMessage()];
            }
        }
        if (count($err) == count($user_ids)) {
            return self::beanErr(collect($err)->map(fn($it)=>"{$it['id']} {$it['msg']}")->first(), 500);
        }
        return self::bean(['success'=>$suc, 'error'=>$err]);
    }

    /** 文件上传 */
    public function upload() {
        $id = request('id');                // 为空是上传
        $type = request('type');            // 可为空
        $file = request()->file('file');
        
        $dir = '/upload/system/sys_user';
        $ext = strtolower($file->getClientOriginalExtension()) ?: 'png';
        $name = date('YmdHisu') .'_'. rand(1000, 9999) .'.'. $ext;
        $file = $file->move(public_path($dir), $name);
        return $this->bean([
            'type'          => $type,
            'url'           => $dir .DIRECTORY_SEPARATOR. $name,
            'name'          => $name,
            'size'          => $file->getSize(),
            'ext'           => $file->guessExtension(),
            'mime'          => $file->getMimeType(),
        ]);
    }
            
    /** excel导出 - 数据大易锁表, 主从? */
    public function export() {
        $_type = request('_type');
        $params = request()->except(['_type']);

        if ($_type == 'sms') {
            // $csvName = 'sys_user' .'-'. $_type .'-'. date('Y-m-d') .'-'. rand(100,999) .'.csv';
            // $sheetTitle = [];
            // $query = SysUserModel::query()
            //     ->select([])
            //     ->when(isset($params['id']), fn($q)=>$q->where('id', '=', $params['id']))
            //     ;
            // export_csv($csvName, $sheetTitle, $query, fn($obj) => [
            //     $obj->id, 
            // ]);
        }

        $csvName = 'sys_user' .'-'. date('Y-m-d') .'-'. rand(100,999) .'.csv';
        $sheetTitle = ['用户ID', '部门ID', '用户账号', '用户昵称', '用户类型（00系统用户）', '用户邮箱', '手机号码', '用户性别（0男 1女 2未知）', '头像地址', '密码', '帐号状态（0正常 1停用）', '删除标志（0代表存在 2代表删除）', '最后登录IP', '最后登录时间', '创建者', '创建时间', '更新者', '更新时间', '备注'];
        $query = SysUserModel::query()
                ->select(['user_id', 'dept_id', 'user_name', 'nick_name', 'user_type', 'email', 'phonenumber', 'sex', 'avatar', 'password', 'status', 'del_flag', 'login_ip', 'login_date', 'create_by', 'create_time', 'update_by', 'update_time', 'remark'])
                // ->when(isset($params['id']), fn($q)=>$q->where('id', '=', $params['id']))
                ;
        export_csv($csvName, $sheetTitle, $query, fn($obj) => [
            $obj->user_id, $obj->dept_id, $obj->user_name, $obj->nick_name, $obj->user_type, $obj->email, $obj->phonenumber, $obj->sex, $obj->avatar, $obj->password, $obj->status, $obj->del_flag, $obj->login_ip, $obj->login_date, $obj->create_by, $obj->create_time, $obj->update_by, $obj->update_time, $obj->remark
        ]);
    }
            
}
    
}
